package top.hzy520.order.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.hzy520.common.exception.YuyuBuyException;
import top.hzy520.common.resp.ApiResult;
import top.hzy520.order.dao.OrderItemMapper;
import top.hzy520.order.dao.OrderMapper;
import top.hzy520.order.dto.OrderDto;
import top.hzy520.order.dto.OrderItemDto;
import top.hzy520.order.dto.OrderPageDto;
import top.hzy520.order.entity.*;
import top.hzy520.order.feign.GoodsServiceClient;
import top.hzy520.order.feign.KeyGeneratorServiceClient;
import top.hzy520.order.feign.StockServiceClient;
import top.hzy520.order.feign.ValuationServiceClient;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 10:54 2018/6/10
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static final Byte ORDER_PAY_SUCCESS = 3;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private KeyGeneratorServiceClient keyGeneratorServiceClient;
    @Autowired
    private StockServiceClient stockClient;
    @Autowired
    private GoodsServiceClient goodsServiceClient;
    @Autowired
    private ValuationServiceClient valuationServiceClient;
    /**
    *@Author: HouZeYu
    *@Description: 创建订单
    *@Date: 11:17 2018/6/10
    */
    @Override
    public OrderDto createOrder(List<OrderItem> orderItemList, Long user_uuid) {
        final BigDecimal[] total = {BigDecimal.ZERO};
        //通过全局ID服务生成订单号
       String orderNo= keyGeneratorServiceClient.keyGenerator();
       //拼装库存扣减需要的参数
       List<ReduceStock> reduceStockList=new ArrayList<>();
       orderItemList.stream().forEach(param->{
           ReduceStock reduceStock=new ReduceStock();
           reduceStock.setOrderNo(Long.valueOf(orderNo));
           reduceStock.setSkuId(param.getSkuId());
           reduceStock.setReduceCount(param.getQuantity());
           reduceStockList.add(reduceStock);
       });
       //扣减库存得到扣减成功的商品id
        ApiResult<Map<Long,Integer>> stockResult=stockClient.stockReduce(reduceStockList);
        Map<Long,Integer> stockMap= stockResult.getData();
        //通过扣减成功的商品id去查找商品详情
       ApiResult<List<ProductSku>> skuResult=goodsServiceClient.selectSkuList(stockMap.keySet());
       List<ProductSku> productSkuList= skuResult.getData();
       //去除没库存的商品
        stockMap.keySet().stream().forEach(param->{
            if (stockMap.get(param)==-1){
            OrderItem orderItem=orderItemList.stream().filter(item->item.getSkuId()==param).findFirst().get();
            orderItemList.remove(orderItem);
            }
        });
        if (orderItemList.size()==0){
            throw new YuyuBuyException("该商品库存不足");
        }
        //计算商品每个商品花费的总价并插入订单详情表并并拼装dto参数
        List<OrderItemDto> orderItemDtoList=new ArrayList<>();
        orderItemList.stream().forEach(param->{
            ProductSku productSku=productSkuList.stream().filter(item->item.getId()==param.getSkuId()).findFirst().get();
            OrderItem orderItem=new OrderItem();
            OrderItemDto orderItemDto=new OrderItemDto();
            orderItem.setOrderNo(Long.valueOf(orderNo));
            orderItem.setUserUuid(user_uuid);
            orderItem.setSkuId(productSku.getId());
            orderItem.setSkuName(productSku.getSkuName());
            orderItemDto.setSkuName(productSku.getSkuName());
            orderItem.setSkuImgUrl(productSku.getImgUrl());
            orderItemDto.setSkuImgUrl(productSku.getImgUrl());
            //调用计价服务计算每个商品参加各种活动后的价格
            BigDecimal price=valuationServiceClient.valuationGoodsPrice(productSku);
            orderItem.setCurrentPrice(price);
            orderItemDto.setCurrentPrice(price);
            orderItem.setQuantity(-param.getQuantity());
            orderItemDto.setQuantity(-param.getQuantity());
            orderItem.setTotalPrice(price.multiply(new BigDecimal(-param.getQuantity())));
            orderItemDto.setTotalPrice(orderItem.getTotalPrice());
            //累加计算总共花费多少金额
            total[0] = total[0].add(price.multiply(new BigDecimal(-param.getQuantity())));
            orderItemDtoList.add(orderItemDto);
            orderItemMapper.insertSelective(orderItem);
        });
        //生成订单表并插入数据库和拼装dto参数
        Order order=new Order();
        OrderDto orderDto=new OrderDto();
        order.setOrderNo(Long.valueOf(orderNo));
        orderDto.setOrderNo(order.getOrderNo());
        orderDto.setPayment(total[0]);
        order.setUserUuid(user_uuid);
        order.setPayment(total[0]);
        orderDto.setOrderItemDtoList(orderItemDtoList);
        orderMapper.insertSelective(order);

        //设置redis监听订单自动关闭
        redisTemplate.opsForValue().set(orderNo,orderNo,30,TimeUnit.SECONDS);
        return orderDto;
    }
    /**
    *@Author: HouZeYu
    *@Description:  分页查询用户的所有订单
    *@Date: 13:58 2018/7/3
    */
    @Override
    public OrderPageDto viewOrder(PageQueryBean pageQueryCodition, Long uuid) {
      Integer count=orderMapper.coutByCondition(uuid);
      List<Order> orderDtoList=orderMapper.selectOrderByUuId(uuid,pageQueryCodition);
        OrderPageDto orderPageDto=new OrderPageDto();
        orderPageDto.setTotalPage(count);
        orderPageDto.setOrderList(orderDtoList);
        return orderPageDto;
    }

    @Override
    public Order queryOrderSubjectById(Long orderNo) {
        return orderMapper.selectOrderByOrderNo(orderNo);
    }

    /***
     *
     * @param order 订单编号
     */
    @Override
    public void verifyOrderStatus(Order order) {
        order.setOrderStatus(ORDER_PAY_SUCCESS);
        order.setCloseTime(new Date());
      orderMapper.updateByPrimaryKeySelective(order);
    }

}
